//
//  HomeController.swift
//  edu
//
//  Created by karlzhou on 15/10/29.
//  Copyright (c) 2015年 karlzhou. All rights reserved.
//

import UIKit
import SwiftyJSON
import ObjectMapper
import SnapKit

enum HomeCellType{
    case Banner
    case Subject
}

class HomeController:UIViewController,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
    
    
    
    var loadingView: UIActivityIndicatorView = UIActivityIndicatorView()
    
    var emptyView: UIButton = UIButton()
    var errorView: UIButton = UIButton()
    
    var  dataSource:[HomeModel]=[]
    let identifier="cellId"
    let headIdentifier="headCellId"
    let banerIdentifier="bannerCellId"
    var collectionView:UICollectionView!
    //var banerCollectionView: UICollectionView!
    var homedatas:[HomeModel]!
    var categoryItem:UIBarButtonItem!
    override func viewDidLoad() {
        super.viewDidLoad()
    
      self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "green_bg_iphone4"), forBarMetrics: .Default)
        self.navigationItem.title=""
        initLeft()
        initRight()
        
        //initBanerView()
        initSubjectView()
        firstRefreshing()
        loadData()
        self.view.backgroundColor = UIColor.whiteColor()
    }
    
    
    func loadData(){
        let success={
            (data:[HomeModel]) -> Void in
            self.dataSource=data
            self.collectionView.reloadData()
        };
        
        let failure = {
            (code:Int,message:String) -> Void in
            // self.endRefreshing()
        }
        
        APIClient.getHomeData(success, failure: failure)
    }
    
    func firstRefreshing() {
        self.loadingView.hidden = false
        self.loadingView.startAnimating()
        self.emptyView.hidden = true
        self.errorView.hidden = true
        // 延时0.3秒后执行加载数据操作，延时是为了Loading不会因为加载速度过快造成一闪而过的不好体验
        self.delay(0.3) { () -> () in
            self.loadData()
        }
    }
    
    func initBanerView(){
        
        
        
    }
    
    func initSubjectView(){
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection=UICollectionViewScrollDirection.Vertical
        //layout.itemSize=CGSize(width: self.view.frame.size.width/2-10 ,height: 200)
        layout.headerReferenceSize=CGSizeMake(self.view.frame.width, 30)
        self.collectionView=UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
        
        let xib=UINib(nibName: "HomeCommonCell", bundle: nil)
        self.collectionView.registerNib(xib, forCellWithReuseIdentifier: identifier)
        self.collectionView.registerClass(BannerCell.self, forCellWithReuseIdentifier: banerIdentifier)
        
        //self.collectionView.pagingEnabled = true
        self.collectionView.backgroundColor = UIColor.whiteColor()
        
        //header
        self.collectionView.registerClass(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: self.headIdentifier)
        
        
        
        self.collectionView.dataSource=self
        self.collectionView.delegate=self
        
        self.view.addSubview(collectionView)
        
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    private func initLeft(){
        
        let logoItem=UIBarButtonItem(image: UIImage(named: "BoT_topLogo"), landscapeImagePhone:nil, style: UIBarButtonItemStyle.Plain, target: self, action: nil)
        
        self.navigationItem.leftBarButtonItems=[logoItem]
    }
    
    private func initRight(){
        
        let searchItem = UIBarButtonItem.itemWithImage("ico_bar_search", highImage: "ico_bar_search_pressed", target: self, action: "toSearchPage")
   
        let historyItem = UIBarButtonItem.itemWithImage("ico_bar_history", highImage: "ico_bar_history_pressed", target: self, action: "toHistoryPage")
   
        let view = UIView(frame: CGRectMake(0,0,40,44))
        view.alpha = 0.0
        let blent = UIBarButtonItem(customView: view)
        self.navigationItem.rightBarButtonItems=[searchItem,blent,historyItem]
    }
    
    func toSearchPage(){
        let searchVC = SearchController()
        
        self.navigationController?.pushViewController(searchVC, animated: true)
    }
    
    func toHistoryPage(){
        
    }
    
    func categoryClick(sender:UIBarButtonItem){
       // print("categoryClick")
        //        let categoryViewContrl = CategoryControllerViewController()
        //        categoryViewContrl.modalPresentationStyle=UIModalPresentationStyle.Popover
        //
        //        let popOverController = categoryViewContrl.popoverPresentationController;
        //        //popOverController.delegate=self
        //        popOverController!.sourceView = sender as? UIView;
        //        popOverController!.sourceRect =
        //        popOverController!.permittedArrowDirections = UIPopoverArrowDirection.Any;
        //        self.presentViewController(categoryViewContrl, animated: true, completion: nil)
        //self.view.addSubview()
        
    }
    
    //设置 item size
  //MARK:
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        if indexPath.section == 0 {
            return CGSizeMake(self.view.frame.size.width, 200)
        }
        return CGSize(width: self.view.frame.size.width/2-5 ,height: 200)
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        if section == 0 {
            return CGSizeMake(0, 0)
        }
        return CGSize(width: self.view.bounds.size.width, height: 30)
    }
    
    func  numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int{
        
        
        return    dataSource.count
        
    }
    
    //@available(iOS 6.0, *)
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        
        if section == 0{
            return 1
        }else{
            return   dataSource[section].vos.count
            
        }
        
    }
    
    
    
    // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
    // @available(iOS 6.0, *)
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        
        var data = dataSource[indexPath.section].vos
        if indexPath.section == 0 {
            let bannerCell = collectionView.dequeueReusableCellWithReuseIdentifier(banerIdentifier, forIndexPath: indexPath) as! BannerCell
            bannerCell.setModel(data)
            return bannerCell
        }
        
        
        let cell=collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! HomeCommonCell
        
           cell.initView(data[indexPath.row])
        return cell;
    }
    
    
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let sr2VC = Sr2ViewController()
        self.navigationController?.pushViewController(sr2VC, animated: true)
    }
    
    
    @available(iOS 6.0, *)
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat{
        return 5
    }
    @available(iOS 6.0, *)
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat{
        return 1;
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets{
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        
    }
    
    @available(iOS 6.0, *)
    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView{
   
        

        let headerCell=collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: headIdentifier, forIndexPath: indexPath)

        if indexPath.section == 0 {
            return headerCell
        }
        
        let label=UILabel(frame: headerCell.bounds)
        label.text = dataSource[indexPath.section].name
        label.font = UIFont.systemFontOfSize(20)
        label.backgroundColor=UIColor.whiteColor()
        
        headerCell.addSubview(label)
        return headerCell
    }
    
    
    
}

